

<!DOCTYPE html>
<html lang="en" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" href="/img/avatar.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Hughie">
  <meta name="keywords" content="">
  
    <meta name="description" content="Redis实战笔记一、短信登录基于Session登录  单机tomcat应⽤登录检验  sesssion保存在浏览器和应⽤服务器会话之间 ⽤户登录成功，服务端会保存⼀个session，当然客户端有⼀个sessionId 客户端会把sessionId保存在cookie中，每次请求都会携带这个sessionId   分布式应⽤中session共享  真实的应⽤不可能单节点部署，所以就有个多节点登录se">
<meta property="og:type" content="article">
<meta property="og:title" content="Redis实战笔记">
<meta property="og:url" content="https://hughie-hy.gitee.io/2022/03/14/Redis%E5%AE%9E%E6%88%98%E7%AC%94%E8%AE%B0/index.html">
<meta property="og:site_name" content="Hughie&#39;s blog">
<meta property="og:description" content="Redis实战笔记一、短信登录基于Session登录  单机tomcat应⽤登录检验  sesssion保存在浏览器和应⽤服务器会话之间 ⽤户登录成功，服务端会保存⼀个session，当然客户端有⼀个sessionId 客户端会把sessionId保存在cookie中，每次请求都会携带这个sessionId   分布式应⽤中session共享  真实的应⽤不可能单节点部署，所以就有个多节点登录se">
<meta property="og:locale" content="en_US">
<meta property="og:image" content="https://hughie-hy.gitee.io/img/redis.jpg">
<meta property="article:published_time" content="2022-03-14T02:39:14.000Z">
<meta property="article:modified_time" content="2022-04-04T05:46:59.049Z">
<meta property="article:author" content="Hughie">
<meta property="article:tag" content="redis">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://hughie-hy.gitee.io/img/redis.jpg">
  
  
  <title>Redis实战笔记 - Hughie&#39;s blog</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hint.css@2/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/github.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"hughie-hy.gitee.io","root":"/","version":"1.8.14","typing":{"enable":true,"typeSpeed":120,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.4.1"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>Hughie</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                Home
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                Archives
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                Categories
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                Tags
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                About
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('/img/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="Redis实战笔记">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2022-03-14 10:39" pubdate>
        March 14, 2022 am
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      1.4k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      13 分钟
    </span>
  

  
  
    
      <!-- 不蒜子统计文章PV -->
      <span id="busuanzi_container_page_pv" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="busuanzi_value_page_pv"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">Redis实战笔记</h1>
            
            <div class="markdown-body">
              <h1 id="Redis实战笔记"><a href="#Redis实战笔记" class="headerlink" title="Redis实战笔记"></a>Redis实战笔记</h1><h2 id="一、短信登录"><a href="#一、短信登录" class="headerlink" title="一、短信登录"></a>一、短信登录</h2><h3 id="基于Session登录"><a href="#基于Session登录" class="headerlink" title="基于Session登录"></a>基于Session登录</h3><p><img src="https://blog-chy.oss-cn-shenzhen.aliyuncs.com/static/image-20220404121046343.png" srcset="/img/loading.gif" lazyload></p>
<ul>
<li><p>单机tomcat应⽤登录检验</p>
<ul>
<li>sesssion保存在浏览器和应⽤服务器会话之间</li>
<li>⽤户登录成功，服务端会保存⼀个session，当然客户端有⼀个sessionId</li>
<li>客户端会把sessionId保存在cookie中，每次请求都会携带这个sessionId</li>
</ul>
</li>
<li><p>分布式应⽤中session共享</p>
<ul>
<li>真实的应⽤不可能单节点部署，所以就有个多节点登录session共享的问题需要解决</li>
<li>tomcat⽀持session共享，但是有⼴播⻛暴；⽤户量⼤的时候，占⽤资源就严重，不推荐</li>
<li>使⽤redis存储token:<ul>
<li>服务端使⽤UUID⽣成随机64位或者128位token，放⼊redis中，然后返回给客户端并存储在cookie中</li>
<li>⽤户每次访问都携带此token，服务端去redis中校验是否有此⽤户即可</li>
</ul>
</li>
</ul>
</li>
</ul>
<h3 id="基于Redis登录"><a href="#基于Redis登录" class="headerlink" title="基于Redis登录"></a>基于Redis登录</h3><p><img src="https://blog-chy.oss-cn-shenzhen.aliyuncs.com/static/image-20220404120602792.png" srcset="/img/loading.gif" lazyload></p>
<p>key要确保唯一性和方便携带：</p>
<p>Redis中的数据要设置有效期</p>
<p><strong>登录拦截器优化</strong></p>
<p>上一版本存在的问题：如果用户一直访问的是不需要登录验证的页面，那么登录状态就不会刷新，因此创建一个拦截器，主要作用就是刷新token有效期，并不起到拦截作用</p>
<p><img src="https://blog-chy.oss-cn-shenzhen.aliyuncs.com/static/image-20220404124920709.png" srcset="/img/loading.gif" lazyload></p>
<h2 id="二、查询缓存"><a href="#二、查询缓存" class="headerlink" title="二、查询缓存"></a>二、查询缓存</h2><p><img src="https://blog-chy.oss-cn-shenzhen.aliyuncs.com/static/image-20220315200912077.png" srcset="/img/loading.gif" lazyload alt="image-20220315200912077"></p>
<p>Redis缓存作用图示</p>
<p><img src="https://blog-chy.oss-cn-shenzhen.aliyuncs.com/static/image-20220315114544510.png" srcset="/img/loading.gif" lazyload></p>
<p>随着数据从数据库缓存到Redis，Redis的命中率也会越来越高，形成良性循环</p>
<p><img src="https://blog-chy.oss-cn-shenzhen.aliyuncs.com/static/image-20220315114733259.png" srcset="/img/loading.gif" lazyload alt="image-20220315114733259"></p>
<h3 id="缓存更新策略"><a href="#缓存更新策略" class="headerlink" title="缓存更新策略"></a>缓存更新策略</h3><p><img src="https://blog-chy.oss-cn-shenzhen.aliyuncs.com/static/image-20220315202220714.png" srcset="/img/loading.gif" lazyload></p>
<p>主要分析一下主动更新策略的选择</p>
<p><img src="https://blog-chy.oss-cn-shenzhen.aliyuncs.com/static/image-20220315202451105.png" srcset="/img/loading.gif" lazyload></p>
<p><em><strong>操作缓存和数据库时有三个问题需要考虑：</strong></em></p>
<p>1.如何保证缓存与数据库的操作的同时成功或失败？</p>
<ul>
<li>单体系统，将缓存与数据库操作放在一个事务</li>
<li>分布式系统，利用TCC等分布式事务方案</li>
</ul>
<p>2.删除缓存还是更新缓存？</p>
<ul>
<li>更新缓存：每次更新数据库都更新缓存，无效写操作较多</li>
<li>除缓存：更新数据库时让缓存失效，查询时再更新缓存</li>
</ul>
<p>3.先操作缓存还是先操作数据库？</p>
<ul>
<li>先删除缓存，再操作数据库  ×（安全问题概率较高）</li>
<li>先操作数据库，再删除缓存  √（在满足原子性的情况下，安全问题概率较多）</li>
</ul>
<p>Redis和MySQL数据不一致的问题</p>
<p><img src="https://blog-chy.oss-cn-shenzhen.aliyuncs.com/static/image-20220315203542738.png" srcset="/img/loading.gif" lazyload></p>
<h3 id="缓存穿透"><a href="#缓存穿透" class="headerlink" title="缓存穿透"></a>缓存穿透</h3><p><strong>缓存穿透</strong>是指客户端请求的数据在缓存中和数据库中都不存在，这样缓存永远不会生效，这些请求都会打到数据库。</p>
<p>常见的解决方案有两种：</p>
<p><strong>缓存空对象</strong></p>
<ul>
<li>优点：实现简单，维护方便</li>
<li>缺点：<ul>
<li>额外的内存消耗</li>
<li>可能造成短期的不一致</li>
</ul>
</li>
</ul>
<p><strong>布隆过滤</strong></p>
<ul>
<li>优点：内存占用较少，没有多余key</li>
<li>缺点：<ul>
<li>实现复杂</li>
<li>存在误判可能（过滤判定不存在则一定不存在，判定存在数据库也可能不存在）</li>
</ul>
</li>
</ul>
<p><img src="https://blog-chy.oss-cn-shenzhen.aliyuncs.com/static/image-20220315203949119.png" srcset="/img/loading.gif" lazyload alt="image-20220315203949119"></p>
<p>逻辑变更</p>
<p><img src="https://blog-chy.oss-cn-shenzhen.aliyuncs.com/static/image-20220315204122395.png" srcset="/img/loading.gif" lazyload></p>
<p>缓存穿透产生的原因是什么？</p>
<ul>
<li>用户请求的数据在缓存中和数据库中都不存在，不断发起这样的请求，给数据库带来巨大压力</li>
</ul>
<p>缓存穿透的解决方案有哪些？</p>
<ul>
<li>缓存null值</li>
<li>布隆过滤</li>
<li>增强id的复杂度，避免被猜测id规律</li>
<li>做好数据的基础格式校验</li>
<li>加强用户权限校验（访问权限）</li>
<li>做好热点参数的限流</li>
</ul>
<h3 id="缓存雪崩"><a href="#缓存雪崩" class="headerlink" title="缓存雪崩"></a>缓存雪崩</h3><p><strong>缓存雪崩</strong>是指在同一时段大量的缓存key同时失效或者Redis服务宕机，导致大量请求到达数据库，带来巨大压力。</p>
<p><img src="https://blog-chy.oss-cn-shenzhen.aliyuncs.com/static/image-20220315164426599.png" srcset="/img/loading.gif" lazyload alt="image-20220315164426599"></p>
<p><strong>解决方案</strong></p>
<ul>
<li><p>给不同的Key的TTL添加随机值（不让大量的key同时失效）</p>
</li>
<li><p>利用Redis集群提高服务的可用性（哨兵模式）</p>
</li>
<li><p>给缓存业务添加降级限流策略（快速失败，服务降级保护）</p>
</li>
<li><p>给业务添加多级缓存（浏览器，Nginx，Redis，Jvm）</p>
</li>
</ul>
<h3 id="缓存击穿"><a href="#缓存击穿" class="headerlink" title="缓存击穿"></a>缓存击穿</h3><p><strong>缓存击穿问题</strong>也叫热点Key问题，就是一个被<strong>高并发访问</strong>（正在做活动的商品）并且<strong>缓存重建业务较复杂</strong>（数据库查询复杂，需要较长时间）的key突然失效了，无数的请求访问会在瞬间给数据库带来巨大的冲击</p>
<p>线程一查询未命中，由于查询时间较长，又是一个热点key。导致无数请求直接达到了数据库。</p>
<p><img src="https://blog-chy.oss-cn-shenzhen.aliyuncs.com/static/image-20220315204500279.png" srcset="/img/loading.gif" lazyload></p>
<p>常见的解决方案有两种：</p>
<ul>
<li>互斥锁</li>
<li>逻辑过期</li>
</ul>
<p><img src="https://blog-chy.oss-cn-shenzhen.aliyuncs.com/static/image-20220315204942961.png" srcset="/img/loading.gif" lazyload></p>
<p>方案分析</p>
<p><img src="https://blog-chy.oss-cn-shenzhen.aliyuncs.com/static/image-20220315205012923.png" srcset="/img/loading.gif" lazyload></p>
<h2 id="三、优惠券秒杀"><a href="#三、优惠券秒杀" class="headerlink" title="三、优惠券秒杀"></a>三、优惠券秒杀</h2><h2 id="Reference"><a href="#Reference" class="headerlink" title="Reference"></a>Reference</h2>
            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/Redis/">Redis</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/redis/">redis</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/03/15/@Autowire%E5%92%8C@Resource/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">注解@Autowired和@Resource</span>
                        <span class="visible-mobile">Previous</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/03/11/Java%E9%9B%86%E5%90%88%E9%81%8D%E5%8E%86%E7%9A%84%E5%87%A0%E7%A7%8D%E6%96%B9%E5%BC%8F/">
                        <span class="hidden-mobile">Java集合遍历</span>
                        <span class="visible-mobile">Next</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
              <!-- Comments -->
              <article class="comments" id="comments" lazyload>
                
                  
                
                

              </article>
            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;TOC</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">Search</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">keyword</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
  </div>
  
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


  

  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/js/local-search.js" ></script>



  
    <script  src="/js/img-lazyload.js" ></script>
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>




  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
        typing(title);
      
    })(window, document);
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>


</body>
</html>
